<?php
namespace App\Services\Admin;

use Illuminate\Support\Facades\DB;

class SceneService extends BaseService
{
    /**
     * 场景
     */

    /**
     * 获取场景连列表
     * @param array $pages【start起始页，limit每页记录数】
     * return array
     */
    public function getIndex($pages)
    {
        $start = ($pages['start'] - 1) * $pages['limit'];
        $db = $this->dbConn($this->dbScene)
            ->where('del', 1);
        $total = $db->count();
        $res = $db->skip($start)->take($pages['limit'])
            ->orderBy('id', 'asc')
            ->get();
        if (!count($res)) {
            return array('code' => -2, 'msg' => '没有了');
        }
        $arys = [];
        foreach ($res as $v) {
            $v = (array) $v;
            $thumb = file_exists($v['thumb']) ? $v['thumb'] : '';
            $attrstr = $v['attr_json'] ? $v['attr_json'] : '';
            $arys[] = [
                'id' => $v['id'],
                'title' => $v['title'],
                'cnt' => $v['cnt'],
                'attr_str' => $attrstr,
                'thumb' => $thumb,
            ];
        }
        return array('code' => 0, 'msg' => 'success', 'data' => $arys, 'total' => $total);
    }

    /**
     * 场景新增
     * @param array $pas
     */
    public function add($pas)
    {
        $pas['uptime'] = $pas['addtime'] = toDate();
        $res = $this->dbConn($this->dbScene)->insertGetId($pas);
        if (!$res) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 场景修改
     * @param int $id
     * @param array $pas
     */
    public function modify($id, $pas)
    {
        $pas['uptime'] = toDate();
        $up = $this->dbConn($this->dbScene)
            ->where('id', $id)
            ->update($pas);
        if (!$up) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }

    /**
     * 场景删除
     * @param id $id 场景ID
     * return array
     */
    public function del($id)
    {
        $pas = [
            'del' => 2,
            'deltime' => toDate(),
        ];
        $res = $this->dbConn($this->dbScene)
            ->where('del', 1)
            ->where('id', $id)
            ->update($pas);
        if (!$res) {
            return $this->toback(-1, 'error');
        }
        return $this->toback();
    }
}